package vn.keho.module.dompeto;

import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import com.bingkaimedia.merchantbeta.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import vn.keho.define.convert.JsonUtil;
import vn.keho.define.gcm.GcmServiceUtil;
import vn.keho.module.dompeto.fragment.BlackFragment;
import vn.keho.module.dompeto.fragment.MainFragment;
import vn.keho.module.dompeto.fragment.MenuFragment;
import vn.keho.module.dompeto.fragment.PageFragment;
import vn.keho.module.dompeto.fragment.PinFragment;
import vn.keho.module.dompeto.fragment.SettingFragment;
import vn.keho.module.dompeto.fragment.ThemeFragment;
import vn.keho.module.dompeto.model.ChannelModel;
import vn.keho.module.dompeto.model.PageModel;
import vn.keho.module.dompeto.model.TestWalletProfile;
import vn.keho.module.dompeto.model.ThemeModel;
import vn.keho.module.dompeto.model.WalletProfile;
import vn.keho.module.dompeto.rest.DompetoDefine;
import vn.keho.module.dompeto.rest.DompetoParam;
import vn.keho.module.dompeto.rest.DompetoRequest;
import vn.keho.module.dompeto.socket.TransactionSocket;
import vn.keho.module.dompeto.sqlite.DompetoSqliteHelper;
import vn.keho.module.dompeto.utils.ThemeUtil;

public class HomeActivity extends FragmentActivity implements PageFragment.OnPageFragmentListener {
    private Button btnMenu, btnCategory, btnHome;
    private Button btnInbox, notifyBadge;
    private static MainFragment instance;

    /**
     * DrawerLayout
     */
    private DrawerLayout drawerLayout;
    private ActionBarDrawerToggle actionBarDrawerToggle;
    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private SettingFragment settingFragment;
    private MenuFragment menuFragment;
    private MainFragment mainFragment;
    private ThemeFragment themeFragment;
    private BlackFragment blackFragment;
    private PinFragment pinFragment;

    private DompetoSqliteHelper dompetoSqliteHelper;

    private ProgressDialog progressDialog;
    private int count = 0;

    private WalletProfile walletProfile;
    private List<PageModel> listPageModel = new ArrayList<PageModel>();


    private TransactionSocket transactionSocket;

    private LinearLayout drawerLayoutContent;


    public static MainFragment getInstance() {
        return instance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);

        dompetoSqliteHelper = new DompetoSqliteHelper(this);

        btnMenu = (Button) findViewById(R.id.btnMenu);
        btnMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
        btnCategory = (Button) findViewById(R.id.btnCategory);
        btnCategory.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                drawerLayout.openDrawer(Gravity.RIGHT);
            }
        });

        btnHome = (Button) findViewById(R.id.btnHome);
        btnHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switchFragment(MainFragment.MAIN_FRAGMENT_ID);
            }
        });

        btnInbox = (Button) findViewById(R.id.btnInbox);
        notifyBadge = (Button) findViewById(R.id.notifyBadge);

        drawerLayoutContent = (LinearLayout) findViewById(R.id.drawerLayoutContent);

        setUpDrawerLayout();

        onLoadTheme();

        switchFragment(MainFragment.MAIN_FRAGMENT_ID);

        transactionSocket = TransactionSocket.getInstance(this);

        String devicetoken = GcmServiceUtil.registerGcm(this);
        Log.i("DeviceToken", devicetoken);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    private void onLoadTheme() {
        ThemeUtil.onActivityCreateSetTheme(drawerLayoutContent);
        onLoadDataFromServer();
    }

    private void onLoadDataFromServer() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoadingDialog(true);

                DompetoParam params = new DompetoParam(DompetoDefine.URL_OPEN_WALLET);
                params.setUsername(DompetoRequest.username);
                params.setAppsidonapps(DompetoRequest.appsidonapps);
                params.setToken(DompetoRequest.token);
                new DompetoRequest(HomeActivity.this, new DompetoRequest.AsyncCallbackRequestHandler() {
                    @Override
                    public void handlerRequestSuccess(Object data) {
                        showLoadingDialog(false);
                        try {
                                String finalData = data.toString().trim();
                                if(finalData.startsWith("[")) {
                                    JSONArray array = new JSONArray(finalData);
                                    finalData = array.get(0).toString();
                                }
                                JSONObject jsWalletProfile = new JSONObject(finalData);
                                if(jsWalletProfile.has("walletprofile")) {
                                    jsWalletProfile = jsWalletProfile.getJSONObject("walletprofile");
                                }

                                walletProfile = new WalletProfile(jsWalletProfile);//JsonUtil.generateJavaObject(jsWalletProfile.toString(), WalletProfile.class);
                                int themId = walletProfile.getThemeid() % ThemeUtil.MAX_THEME;

                            String testjs = "{\"size\":100}";
                            TestWalletProfile test = new TestWalletProfile();
                            test.setSize(200);
                            Log.i("Test0", test.getSize() + " - " + JsonUtil.buildJsonString(test));
                            test = JsonUtil.generateJavaObject(testjs, TestWalletProfile.class);
                            Log.i("Test", test.getSize() + " - " + JsonUtil.buildJsonString(test));

                                Log.i("Page Size", (walletProfile.getPagesize()) + " - " + JsonUtil.buildJsonString(walletProfile) + "-" + jsWalletProfile.toString());
                                if(walletProfile.getPagesize() > 0) {
                                    listPageModel = walletProfile.getPages();

                                    for(PageModel pageModel : listPageModel) {
                                        for(int j = pageModel.getSlots().size(); j < walletProfile.getChannelperpagesize(); j++) {
                                            ChannelModel channelModel = new ChannelModel("false", j + 1);
                                            pageModel.getSlots().add(channelModel);
                                        }
                                    }

                                    if(ThemeUtil.sTheme != themId) {
                                        ThemeUtil.changeToTheme(drawerLayoutContent, themId);
                                    }
                                    if(mainFragment != null) {
                                        mainFragment.reloadData(listPageModel);
                                    }
                                }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void handlerRequestError(String message) {
                        Log.i("Response", message);
                        //showLoadingDialog(false);
                    }
                }).executeStart(params);
            }
        });
    }

    public void onSyncWithServer() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    DompetoParam params = new DompetoParam(DompetoDefine.URL_UPDATE_WALLET);
                    JSONArray jsonParam = new JSONArray();
                    JSONObject param1 = new JSONObject();
                    param1.put("username", DompetoRequest.username);
                    param1.put("appsidonapps", DompetoRequest.appsidonapps);
                    param1.put("token", DompetoRequest.token);
                    jsonParam.put(param1);

                    //String test = "{\"walletprofile\":{\"themeslot\":\"2\",\"themebackground\":\"2\",\"pages\":[{\"title\":\"Discount Card\",\"slots\":[{\"channelid\":\"false\",\"slotid\":1},{\"channelid\":\"1\",\"channeltitle\":\"matahari\",\"imageurl\":\"http:\\/\\/www.dompeto.com\\/static\\/images\\/channels\\/matahari.png\",\"slotid\":3},{\"channelid\":\"false\",\"slotid\":3},{\"channelid\":\"false\",\"slotid\":4},{\"channelid\":\"false\",\"slotid\":5}],\"pageid\":1},{\"title\":\"Discount Card\",\"slots\":[{\"channelid\":\"false\",\"slotid\":2},{\"channelid\":\"false\",\"slotid\":2},{\"channelid\":\"false\",\"slotid\":3},{\"channelid\":\"false\",\"slotid\":4},{\"channelid\":\"1\",\"channeltitle\":\"matahari\",\"imageurl\":\"http:\\/\\/www.dompeto.com\\/static\\/images\\/channels\\/matahari.png\",\"slotid\":3}],\"pageid\":1}],\"pagesize\":1,\"channelsize\":2,\"themeid\":0,\"channelperpagesize\":0}}";

                    JSONObject param2 = new JSONObject();
                    param2.put("walletprofile", walletProfile.toJSON());
                    jsonParam.put(param2);
                    JSONObject param3 = new JSONObject();
                    JSONArray pageArray = new JSONArray();
                    for(PageModel pageModel : listPageModel) {
                        pageArray.put(pageModel.toJSON());
                    }
                    param3.put("pages", pageArray);
                    jsonParam.put(param3);
                    String resultParam = jsonParam.toString();//JsonUtil.buildJsonString(jsonParam);
                    Log.i("Param", resultParam);
                    if (listPageModel == null || listPageModel.isEmpty()) {
                        return;
                    } else if (true) {
                        //return;
                    }
                    params.setUpdatewallet(resultParam);
                    new DompetoRequest(HomeActivity.this, new DompetoRequest.AsyncCallbackRequestHandler() {
                        @Override
                        public void handlerRequestSuccess(Object data) {

                            try {
                                Log.i("Result", data.toString());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void handlerRequestError(String message) {
                            Log.i("Response", message);
                            showLoadingDialog(true);
                        }
                    }).executeStart(params);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void showLoadingDialog(boolean isShow) {
        if(isShow) {
            if(progressDialog == null) {
                progressDialog = new ProgressDialog(this, R.style.DompetoDialog);
                progressDialog.setMessage("Please wait...");
                progressDialog.setTitle("Sync with server");
                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                progressDialog.setCanceledOnTouchOutside(false);
            }
            if(!progressDialog.isShowing()) {
                progressDialog.show();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        count=30;
                        try {
                            while (count >= 0) {
                                Thread.sleep(1000);

                                handle.sendMessage(handle.obtainMessage());
                                count--;
                                if (count <= 1) {
                                    if(progressDialog.isShowing()) {
                                        progressDialog.dismiss();
                                    }
                                }
                            }
                        }
                        catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        } else {
            if(progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
                count = 0;
            }
        }
    }

    private Handler handle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            progressDialog.setMessage("Please wait..." + count);
        }
    };


    public void setUpDrawerLayout() {
        settingFragment = (SettingFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_right);
        menuFragment = (MenuFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer_left);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        // set a custom shadow that overlays the main content when the drawer opens
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        //mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        //mDrawerLayout.setDrawerShadow(new ColorDrawable(Color.TRANSPARENT), GravityCompat.START);
        // set up the drawer's list view with items and click listener

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,                    /* host Activity */
                drawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_launcher,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (drawerView.getId() == R.id.navigation_drawer_right) {
                    if (!settingFragment.isAdded()) {
                        return;
                    }
                } else if (drawerView.getId() == R.id.navigation_drawer_left) {
                    if (!menuFragment.isAdded()) {
                        return;
                    }
                }

                supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);

                if (drawerView.getId() == R.id.navigation_drawer_right) {
                    if (!settingFragment.isAdded()) {
                        return;
                    }
                } else if (drawerView.getId() == R.id.navigation_drawer_left) {
                    if (!menuFragment.isAdded()) {
                        return;
                    }
                }

                supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                super.onDrawerSlide(drawerView, slideOffset);

                LinearLayout frameLayout = (LinearLayout) findViewById(R.id.drawerLayoutContent);
                if (drawerView.getId() == R.id.navigation_drawer_right) {
                    frameLayout.setX(-slideOffset * drawerView.getWidth());
                } else {
                    frameLayout.setX(slideOffset * drawerView.getWidth());
                }

            }
        };
        // Defer code dependent on restoration of previous instance state.
        drawerLayout.post(new Runnable() {
            @Override
            public void run() {
                actionBarDrawerToggle.syncState();
            }
        });

        drawerLayout.setDrawerListener(actionBarDrawerToggle);
    }

    private int currentFragmentIndex = MainFragment.MAIN_FRAGMENT_ID;

    private void switchFragment(int fragmentIndex) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (fragmentIndex != currentFragmentIndex) {
            //Remove
            switch (currentFragmentIndex) {
                case MainFragment.MAIN_FRAGMENT_ID:
                    if (mainFragment != null && !mainFragment.isDetached()) {
                        //transaction.detach(mainFragment);
                    }
                    break;
                case ThemeFragment.THEME_FRAGMENT_ID:
                    if (themeFragment != null && !themeFragment.isDetached()) {
                        transaction.detach(themeFragment);
                    }
                    break;
                case BlackFragment.BLACK_FRAGMENT_ID:
                    if(blackFragment != null && !blackFragment.isDetached()) {
                        transaction.detach(blackFragment);
                    }
                    break;
                case PinFragment.PIN_FRAGMENT_ID:
                    if(pinFragment != null && !pinFragment.isDetached()) {
                        transaction.detach(pinFragment);
                    }
                    break;
            }
        }
        currentFragmentIndex = fragmentIndex;
        switch (fragmentIndex) {
            case MainFragment.MAIN_FRAGMENT_ID:
                if (mainFragment == null) {
                    mainFragment = MainFragment.newInstance();
                    transaction.add(R.id.fragmentContent, mainFragment);

                    instance = mainFragment;

                    instance.reloadData(listPageModel);
                } else {
                    //transaction.attach(mainFragment);
                }

                break;
            case ThemeFragment.THEME_FRAGMENT_ID:
                if (themeFragment == null) {
                    themeFragment = ThemeFragment.newInstance();
                    transaction.add(R.id.fragmentContent, themeFragment);
                } else {
                    transaction.attach(themeFragment);
                }
                break;
            case BlackFragment.BLACK_FRAGMENT_ID:
                if(blackFragment == null) {
                    blackFragment = BlackFragment.newInstance();
                    transaction.add(R.id.fragmentContent, blackFragment);
                } else {
                    transaction.attach(blackFragment);
                    blackFragment.refreshData();
                }
                break;
            case PinFragment.PIN_FRAGMENT_ID:
                if(pinFragment == null) {
                    pinFragment = PinFragment.newInstance();
                    transaction.add(R.id.fragmentContent, pinFragment);
                } else {
                    transaction.attach(pinFragment);
                }
                break;
            default:

                break;
        }

        transaction.commit();
        getSupportFragmentManager().executePendingTransactions();
    }

    public void onSettingThemeClick(View btn) {
        drawerLayout.closeDrawers();
        switchFragment(ThemeFragment.THEME_FRAGMENT_ID);
    }

    public void onSettingBlackClick(View btn) {
        drawerLayout.closeDrawers();
        switchFragment(BlackFragment.BLACK_FRAGMENT_ID);
    }

    public void onSettingPinClick(View btn) {
        drawerLayout.closeDrawers();
        switchFragment(PinFragment.PIN_FRAGMENT_ID);
    }

    public void onThemeChange(View btn) {
        switch (btn.getId()) {
            case R.id.imgTheme1:
                walletProfile.setThemeid(ThemeUtil.THEME_FIRST);
                ThemeUtil.sTheme = ThemeUtil.THEME_FIRST;
                onSyncWithServer();
                ThemeUtil.changeToTheme(drawerLayoutContent, ThemeUtil.THEME_FIRST);

                if(mainFragment != null) {
                    mainFragment.reloadData(listPageModel);
                }
                switchFragment(MainFragment.MAIN_FRAGMENT_ID);
                break;
            default:
                walletProfile.setThemeid(ThemeUtil.THEME_SECOND);
                ThemeUtil.sTheme = ThemeUtil.THEME_SECOND;
                onSyncWithServer();
                ThemeUtil.changeToTheme(drawerLayoutContent, ThemeUtil.THEME_SECOND);

                if(mainFragment != null) {
                    mainFragment.reloadData(listPageModel);
                }
                switchFragment(MainFragment.MAIN_FRAGMENT_ID);
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        transactionSocket.onDestroy();
    }

    public void onInboxUpdateNotify(int notifyNumber) {
        notifyBadge.setText(notifyNumber + "");
        if(notifyNumber == 0) {
            notifyBadge.setVisibility(View.INVISIBLE);
        } else {
            notifyBadge.setVisibility(View.VISIBLE);
        }
    }
}
